package com.micro.ai.models.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.micro.ai.commons.exception.BusinessException;
import com.micro.ai.models.entity.ModelEvaluation;
import com.micro.ai.models.mapper.ModelEvaluationMapper;
import com.micro.ai.models.service.ModelEvaluationService;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


/**
 * 模型评估服务实现
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@Service
public class ModelEvaluationServiceImpl extends ServiceImpl<ModelEvaluationMapper, ModelEvaluation> implements ModelEvaluationService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ModelEvaluation create(ModelEvaluation evaluation) {
        if (evaluation == null) {
            throw new BusinessException("M0000", "评估信息不能为空");
        }
        
        if (evaluation.getStatus() == null) {
            evaluation.setStatus("running");
        }
        
        boolean success = this.save(evaluation);
        if (!success) {
            throw new BusinessException("M0003", "创建评估失败");
        }
        
        log.info("创建模型评估成功: evalId={}, evalName={}", evaluation.getId(), evaluation.getEvaluationName());
        return evaluation;
    }

    @Override
    public Page<ModelEvaluation> pageQuery(int pageNum, int pageSize, String tenantId, String modelId) {
        if (pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize < 1 || pageSize > 100) {
            pageSize = 20;
        }
        
        Page<ModelEvaluation> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<ModelEvaluation> query = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(tenantId)) {
            query.eq(ModelEvaluation::getTenantId, tenantId);
        }
        if (StringUtils.hasText(modelId)) {
            query.eq(ModelEvaluation::getModelId, modelId);
        }
        
        query.orderByDesc(ModelEvaluation::getCreatedAt);
        
        return this.page(page, query);
    }

    @Override
    public Page<ModelEvaluation> listByModelId(String modelId) {
        LambdaQueryWrapper<ModelEvaluation> query = new LambdaQueryWrapper<>();
        query.eq(ModelEvaluation::getModelId, modelId)
             .orderByDesc(ModelEvaluation::getCreatedAt);
        
        return this.page(new Page<>(1, 100), query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ModelEvaluation update(String id, ModelEvaluation evaluation) {
        if (!StringUtils.hasText(id)) {
            throw new BusinessException("M0000", "评估ID不能为空");
        }
        if (evaluation == null) {
            throw new BusinessException("M0000", "评估信息不能为空");
        }
        
        ModelEvaluation existing = this.getById(id);
        if (existing == null) {
            throw new BusinessException("M0002", "模型评估不存在: " + id);
        }
        
        evaluation.setId(id);
        
        boolean success = this.updateById(evaluation);
        if (!success) {
            throw new BusinessException("M0003", "更新评估失败");
        }
        
        log.info("更新模型评估成功: evalId={}", id);
        return evaluation;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String id) {
        if (!StringUtils.hasText(id)) {
            throw new BusinessException("M0000", "评估ID不能为空");
        }
        
        ModelEvaluation evaluation = this.getById(id);
        if (evaluation == null) {
            throw new BusinessException("M0002", "模型评估不存在: " + id);
        }
        
        boolean success = this.removeById(id);
        if (!success) {
            throw new BusinessException("M0003", "删除评估失败");
        }
        
        log.info("删除模型评估成功: evalId={}, evalName={}", id, evaluation.getEvaluationName());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void startEvaluation(String id) {
        if (!StringUtils.hasText(id)) {
            throw new BusinessException("M0000", "评估ID不能为空");
        }
        
        ModelEvaluation evaluation = this.getById(id);
        if (evaluation == null) {
            throw new BusinessException("M0002", "模型评估不存在: " + id);
        }
        
        if (!"pending".equals(evaluation.getStatus()) && !"stopped".equals(evaluation.getStatus())) {
            throw new BusinessException("M0000", "评估状态不正确，只有pending或stopped状态的评估才能启动");
        }
        
        evaluation.setStatus("running");
        
        boolean success = this.updateById(evaluation);
        if (!success) {
            throw new BusinessException("M0003", "启动评估失败");
        }
        
        log.info("启动模型评估: evalId={}, evalName={}", id, evaluation.getEvaluationName());
        
        // 异步执行评估（避免阻塞）
        executeEvaluationAsync(evaluation);
    }
    
    @Autowired(required = false)
    private ModelEvaluationExecutor evaluationExecutor;
    
    @Autowired
    private com.micro.ai.models.service.ModelConfigService modelConfigService;
    
    @Autowired
    private com.micro.ai.models.service.DatasetRecordService datasetRecordService;
    
    /**
     * 异步执行评估
     */
    private void executeEvaluationAsync(com.micro.ai.models.entity.ModelEvaluation evaluation) {
        // 使用异步方式执行评估（实际应该使用@Async或消息队列）
        
        if (evaluationExecutor != null) {
            try {
                // 1. 获取模型配置
                com.micro.ai.models.entity.ModelConfig modelConfig = 
                    modelConfigService.getDefaultConfigByModelId(evaluation.getModelId());
                if (modelConfig == null) {
                    throw new BusinessException("M0002", "模型配置不存在");
                }
                
                // 2. 获取评估数据集记录
                LambdaQueryWrapper<com.micro.ai.models.entity.DatasetRecord> recordQuery = 
                    new LambdaQueryWrapper<>();
                recordQuery.eq(com.micro.ai.models.entity.DatasetRecord::getDatasetId, 
                              evaluation.getEvalDatasetId())
                           .eq(com.micro.ai.models.entity.DatasetRecord::getIsValid, true);
                List<com.micro.ai.models.entity.DatasetRecord> testRecords = 
                    datasetRecordService.list(recordQuery);
                
                if (testRecords.isEmpty()) {
                    throw new BusinessException("M0000", "评估数据集为空");
                }
                
                // 3. 运行评估
                ModelEvaluationExecutor.EvaluationResult result = evaluationExecutor.runEvaluation(
                    modelConfig,
                    testRecords,
                    evaluation.getEvaluationName()
                );
                
                // 4. 保存评估结果
                evaluation.setOverallScore(result.getOverallScore());
                evaluation.setMetrics(com.alibaba.fastjson2.JSON.toJSONString(result.getMetrics()));
                evaluation.setDetailedResults(com.alibaba.fastjson2.JSON.toJSONString(result.getDetailedResults()));
                evaluation.setEvaluatedSamples(testRecords.size());
                evaluation.setStatus("completed");
                evaluation.setCompletedAt(LocalDateTime.now());
                this.updateById(evaluation);
                
                log.info("模型评估完成: evalId={}, overallScore={}", 
                        evaluation.getId(), result.getOverallScore());
                
            } catch (Exception e) {
                log.error("执行模型评估失败: evalId={}, error={}", 
                        evaluation.getId(), e.getMessage(), e);
                evaluation.setStatus("failed");
                evaluation.setErrorMessage(e.getMessage());
                this.updateById(evaluation);
            }
        } else {
            log.warn("评估执行器未配置，跳过实际评估: evalId={}", evaluation.getId());
            // 如果不需要实际评估，直接设置为completed
            evaluation.setStatus("completed");
            evaluation.setOverallScore(0.0);
            evaluation.setCompletedAt(LocalDateTime.now());
            this.updateById(evaluation);
        }
    }
}

